import axios from "axios";
import {BASE_URL, TIMEOUT} from "@/services/request/config";
import useMain from "@/stores/modules/main";

const mainStore = useMain()

class _obRequest {
   constructor(baseURL, timeout = TIMEOUT) {
      this.instance = axios.create({baseURL, timeout})

      //请求成功的拦截器
      this.instance.interceptors.request.use(config => {
         //发送失败不会到个回调函数，会直接回到请求失败的回调函数
         mainStore.isLoading = true
         return config
      }, err => {
         return err
      })

      //请求失败的拦截器
      this.instance.interceptors.response.use(res => {
         mainStore.isLoading = false
         return res
      }, err => {
         mainStore.isLoading = false
         return err
      })
   }

   async request(config) {
      const res = await this.instance.request(config)
      return res.data
   }

   get(config) {
      return this.request({...config, method: 'GET'})
   }

   post(config) {
      return this.request({...config, method: 'POST'})
   }
}

export default new _obRequest(BASE_URL)